package edu.aut.bme.hu.orkomet.settings;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class SettingsManager {
	private static File settingsFile= new File("Settings.xml");
	private static JAXBContext xmlContext;
	
	private static JAXBContext getXmlContext()
	{
		if(xmlContext!=null) return xmlContext;
		try {
			xmlContext= JAXBContext.newInstance("edu.aut.bme.hu.orkomet.settings");
		} catch (JAXBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return xmlContext;
	}
	
	
	public Settings loadSettings()
	{
		Settings retVal=null;
		try {
			Logger.getLogger(SettingsManager.class.getName()).log(Level.INFO,"Loading settings...");
			Unmarshaller um= getXmlContext().createUnmarshaller();
		
			InputStream input;
			if(settingsFile.exists())
				input=new FileInputStream(settingsFile);
			else
				input=SettingsManager.class.getResourceAsStream("Settings.xml");
			retVal=(Settings)(um.unmarshal(input));		
			Logger.getLogger(SettingsManager.class.getName()).log(Level.INFO,"Settings loaded");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return retVal;
	}
	
	public void saveSettings(Settings data)
	{
		try {
			Marshaller m=getXmlContext().createMarshaller();
			m.marshal(data, new FileOutputStream(settingsFile));
			Logger.getLogger(SettingsManager.class.getName()).log(Level.INFO,"Settings saved");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
